﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Common.Services;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Utilities;

namespace Eneta.Portal.Companies
{
    public class CompanyEditPage : Page
    {
        protected HtmlControl warningBox;
        protected Repeater errorsRepeater;
        protected HtmlInputHidden fromUrlField;

        protected Literal titleLabel;
        protected Label fileNameLabel;

        protected TextBox nameField;
        protected TextBox descriptionField;

        protected FileUpload logoUpload;
        protected HtmlImage logoExample;

        //protected TextBox addressField;
        protected TextBox streetField;
        protected TextBox zipField;
        protected TextBox cityField;
        protected CheckBoxList officesList;

        protected TextBox phoneField;
        protected TextBox faxField;
        protected TextBox emailField;

        protected TextBox urlField;
        protected DropDownList employeesList;
        //protected DropDownList certifiedEmployeesList;
        protected TextBox certifiedEmployeesField;
        protected DropDownList partnershipLevel;

        protected TextBox contactField;
        protected TextBox contactEmailField;
        protected TextBox contactPhoneField;

        protected Repeater IOLevel1Repeater;
        protected Button saveButton;
        protected HtmlAnchor cancelLink;

        private Dictionary<string, string> _errors = new Dictionary<string, string>();
        private int _id;

        private CompanyRepository _companyRepository;

        private CompanyRepository CompanyRepository
        {
            get
            {
                if (_companyRepository != null)
                    return _companyRepository;

                _companyRepository = new CompanyRepository(SPContext.Current.Web);
                return _companyRepository;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            EnableViewState = true;

            IOLevel1Repeater.ItemDataBound += IoLevel1RepeaterItemDataBound;
            saveButton.Click += SaveButtonClick;
            errorsRepeater.ItemDataBound += ErrorsRepeaterItemDataBound;
        }

        protected void ErrorsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var label = (Label)e.Item.FindControl("errorLabel");
            label.Text = e.Item.DataItem.ToString();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            ApplyErrors(_errors);

            if (string.IsNullOrEmpty(urlField.Text) || urlField.Text.ToLower() == "http://")
            {
                urlField.CssClass = "text-go clear";
                urlField.Text = "http://";
            }
            else
                urlField.CssClass = "text-go";

            if (string.IsNullOrEmpty(streetField.Text))
                streetField.Text = Resources.Companies.StreetPlaceholder;

            if (streetField.Text == Resources.Companies.StreetPlaceholder)
                streetField.CssClass = "text-go clear";
            else
                streetField.CssClass = "text-go";

            if (string.IsNullOrEmpty(contactPhoneField.Text))
                contactPhoneField.Text = Resources.Companies.PhonePlaceholder;

            if (contactPhoneField.Text == Resources.Companies.PhonePlaceholder)
                contactPhoneField.CssClass = "text-go clear";
            else
                contactPhoneField.CssClass = "text-go";

            SetCheckStyles(Controls);
        }

        private static void SetCheckStyles(ControlCollection controls)
        {
            foreach (Control c in controls)
                if (c.GetType() == typeof(CheckBox))
                    ((CheckBox)c).InputAttributes["class"] = "choice";
                else if (c.HasControls())
                    SetCheckStyles(c.Controls);

        }

        protected void SaveButtonClick(object sender, EventArgs e)
        {
            var codeLoc = string.Empty;
            var pageName = string.Empty;
            var currentUser = SPContext.Current.Web.CurrentUser;
            var isNew = false;
            var id = 0;
            var selectedTopics = GetSelectedTopics();
            var wasAccepted = false;

            if (Item != null)
                if (Item.Status == SPModerationStatusType.Approved)
                    wasAccepted = true;

            

            if (string.IsNullOrEmpty(nameField.Text))
            {
                _errors.Add("name", Resources.Companies.CompanyNameRequired);
            }
            else if (nameField.Text.Length < 4)
            {
                _errors.Add("name", Resources.Companies.CompanyNameTooShort);
            }
            else if (Item == null && CompanyRepository.CompanyExists(nameField.Text))
            {
                _errors.Add("name", Resources.Companies.CompanyAlreadyExists);
            }
            else if (nameField.Text.Length > 50)
            {
                _errors.Add("name", Resources.Companies.CompanyNameTooLong);
            }
            if (string.IsNullOrEmpty(descriptionField.Text))
            {
                _errors.Add("description", Resources.Companies.DescriptionRequired);
            }
            if (string.IsNullOrEmpty(streetField.Text) || streetField.Text == Resources.Companies.StreetPlaceholder)
            {
                _errors.Add("street", Resources.Companies.AddressRequired);
            }
            else if (streetField.Text.Length > 255)
            {
                _errors.Add("street", Resources.Companies.AddressTooLong);
            }

            if (string.IsNullOrEmpty(zipField.Text))
            {
                _errors.Add("zip", Resources.Companies.ZipRequired);
            }
            else if (zipField.Text.Length > 15)
            {
                _errors.Add("zip", Resources.Companies.ZipTooLong);
            }

            if (string.IsNullOrEmpty(cityField.Text))
            {
                _errors.Add("city", Resources.Companies.CityRequired);
            }
            else if (cityField.Text.Length > 255)
            {
                _errors.Add("city", Resources.Companies.CityTooLong);
            }

            if (officesList.SelectedItems().Count == 0)
            {
                _errors.Add("offices", Resources.Companies.SelectOfficeLocation);
            }            

            if(string.IsNullOrEmpty(urlField.Text) || urlField.Text == "http://")
            {
                _errors.Add("url", Resources.Companies.HomePageMissing);
            }
            else if(urlField.Text.Length > 255)
            {
                _errors.Add("url", Resources.Companies.HomePageTooLong);
            }

            int cert;
            if (string.IsNullOrEmpty(certifiedEmployeesField.Text))
            {
                certifiedEmployeesField.Text = "0";
            }
            if (!int.TryParse(certifiedEmployeesField.Text, out cert))
            {
                _errors.Add("cert", Resources.Companies.CertifiedEmployeesHasIncorrectFormat);
            }
            else
            {
                cert = int.Parse(certifiedEmployeesField.Text);
                if (cert < 0)
                    _errors.Add("cert", Resources.Companies.CertifiedEmployeesTooSmall);
                else if (cert > 1000)
                    _errors.Add("cert", Resources.Companies.CertifiedEmployeesTooBig);
            }

            if (contactField.Text.Length > 50)
            {
                _errors.Add("contact", Resources.Companies.ContactNameTooLong);
            }

            if (contactEmailField.Text.Length > 100)
            {
                _errors.Add("contactEmail", Resources.Companies.ContactEmailTooLong);
            }

            if (contactPhoneField.Text.Length > 50)
            {
                _errors.Add("contantPhone", Resources.Companies.ContactPhoneTooLong);
            }

            if (selectedTopics.Length == 0)
            {
                _errors.Add("io", Resources.Companies.SelectCompetency);
            }

            if (!CompanyRepository.CompanyLayoutExists())
                _errors.Add("layout", Resources.Companies.CompanyLayoutNotFound);
            
            if (_errors.Count > 0)
            {
                Logger.LogInfo("Error collection is not empty",GetType().ToString());
                return;
            }

            if (contactPhoneField.Text == Resources.Companies.PhonePlaceholder)
                contactPhoneField.Text = string.Empty;
            if (urlField.Text == "http://")
                urlField.Text = string.Empty;

            var siteId = SPContext.Current.Site.ID;
            var webId = SPContext.Current.Web.ID;            
            var redir = string.Empty;
            var oldName = string.Empty;

            var userId = SPContext.Current.Web.CurrentUser.LoginName;
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (var pubsite = new SPSite(siteId))
                using (var pubweb = pubsite.OpenWeb("/firmad/"))
                {
                    pubweb.AllowUnsafeUpdates = true;
                    var pubList = pubweb.Lists["Lehed"];

                    var cuser = pubweb.SiteUsers[userId];

                    var assq = from a in pubList.RoleAssignments.Cast<SPRoleAssignment>()
                               from r in a.RoleDefinitionBindings.Cast<SPRoleDefinition>()
                               where a.Member.Name == cuser.LoginName &&
                                     r.Name == "Kinnitamine"
                               select a;

                    if (assq.Count() == 0)
                    {
                        Logger.LogInfo("SaveButtonClick(): assq is 0", GetType().ToString());
                        var ass2 = new SPRoleAssignment(cuser);
                        var rb2 = pubweb.RoleDefinitions["Kinnitamine"];
                        Logger.LogInfo("SaveButtonClick(): pubList.RoleAssignments = " + pubList.RoleAssignments.Count, GetType().ToString());
                        ass2.RoleDefinitionBindings.Add(rb2);
                        pubList.RoleAssignments.Add(ass2);
                        pubList.Update();
                    }
                    pubweb.AllowUnsafeUpdates = false;

                }
            });

            try
            {

                var site = SPContext.Current.Site;
                var web = SPContext.Current.Web;
                //var mainSec = new SPSecurity.CodeToRunElevated(delegate
                //{
                    //using (var site = new SPSite(siteId))
                    //{
                        //using (var web = site.AllWebs[webId])
                        //{
                            //site.AllowUnsafeUpdates = true;
                            //web.AllowUnsafeUpdates = true;

                            SPListItem item = null;
                            if(Item != null)
                                try
                                {
                                    item = web.Lists["Lehed"].GetItemById(Item.Id);
                                }
                            catch (Exception ex)
                            {
                                Logger.LogInfo("Cannot find item: " + ex,GetType().ToString());

                            }
                            PublishingPage publishingPage = null;

                            if (item == null)
                            {
                                Logger.LogInfo("SaveButton_Click(): item is null", GetType().ToString());
                                var list = SPContext.Current.Web.Lists["Lehed"]; // web.Lists["Lehed"];
                                Logger.LogInfo("SaveButton_Click(): got list lehed", GetType().ToString());
                                pageName = UrlHelper.GetPageFileName(nameField.Text);

                                codeLoc = "Enne faili";
                                Logger.LogInfo("SaveButton_Click(): looking for file", GetType().ToString());
                                var fileExists = false;
                                var asiteId = SPContext.Current.Site.ID;
                                var awebId = SPContext.Current.Web.ID;
                                var sec = new SPSecurity.CodeToRunElevated(delegate
                                                                               {
                                                                                   using (
                                                                                       var asite = new SPSite(asiteId))
                                                                                   using (
                                                                                       var aweb = asite.OpenWeb(awebId))
                                                                                   {
                                                                                       var afile =
                                                                                           aweb.GetFile(
                                                                                               list.RootFolder.
                                                                                                   ServerRelativeUrl +
                                                                                               "/" + pageName);
                                                                                       fileExists = afile.Exists;
                                                                                   }
                                                                               });
                                SPSecurity.RunWithElevatedPrivileges(sec);

                                //var file = web.GetFile(list.RootFolder.ServerRelativeUrl + "/" + pageName);
                                if (fileExists)
                                {
                                    // Kuidas me selle olukorra laheypdame nii et kasutajad peast segi ei lähe?
                                    Logger.LogInfo("SaveButtonClick: Juba olemas!", GetType().ToString());
                                    return;
                                }
                                Logger.LogInfo("SaveButtonClick: Faili pole!", GetType().ToString());
                                var wasApprover = false;
                                try
                                {
                                    //var companyLayout = CompanyRepository.GetCompanyLayout();
                                    if (web == null)
                                        web = SPContext.Current.Web;
                                    if (site == null)
                                        site = web.Site;
                                    var publishingWeb = PublishingWeb.GetPublishingWeb(web);

                                    Logger.LogInfo("SaveButtonClick: Getting Firma content-type", "CompanyEditPage");
                                    var ct = web.AvailableContentTypes["Firma"];
                                    //Logger.LogInfo("CTS: " +web.ContentTypes.Count, "CompanyEditPage");
                                    //foreach(SPContentType ct2 in web.AvailableContentTypes)
                                    //    Logger.LogInfo("SaveButtonClick: CT: " + ct2.Name, "CompanyEditPage");
                                    if(ct == null)
                                        Logger.LogInfo("SaveButtonClick: company layout: CT Firma is null","CompanyEditPage");

                                    Logger.LogInfo("SaveButtonClick: Getting Firma layouts", "CompanyEditPage");
                                    var companyLayout = publishingWeb.GetAvailablePageLayouts(ct.Id)[0];
                                    Logger.LogInfo("SaveButtonClick: company layout: " + companyLayout,
                                                   "CompanyEditPage");

                                    Logger.LogInfo(
                                        "SaveButtonClick: before publishingWeb.GetPublishingPages().Add - " + pageName,
                                        GetType().ToString());
                                    PublishingPageCollection pages = null;

                                    //SPSecurity.RunWithElevatedPrivileges(delegate
                                    // {
                                    //     using (var pubsite = new SPSite(siteId))
                                    //     using (var pubweb = pubsite.OpenWeb("/firmad/"))
                                    //     {
                                    //         var pubweb2 = PublishingWeb.GetPublishingWeb(pubweb);
                                    //         pages = pubweb2.GetPublishingPages();
                                    //     }
                                    // });
                                    pages = publishingWeb.GetPublishingPages();
                                    Logger.LogInfo("SaveButtonClick: publishing pages retrieved", "CompanyEditPage");
                                    var pageUrl = list.RootFolder.ServerRelativeUrl + "/" + pageName;




                                    publishingPage = pages.Add(pageUrl, companyLayout);

                                    Logger.LogInfo("SaveButtonClick: Publishing page created", "CompanyEditPage");
                                    _id = publishingPage.ListItem.ID;
                                    publishingPage.ListItem["Title"] = nameField.Text;
                                    publishingPage.Update();

                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex);
                                    Response.Write(ex.ToString());
                                    Response.End();
                                }
                                //publishingPage.CheckOut();
                                item = publishingPage.ListItem;
                                Logger.LogInfo("SaveButtonClick: Checkin after new", "CompanyEditPage");
                                publishingPage.CheckIn("");
                                
                                _id = item.ID;
                                var loginName = SPContext.Current.Web.CurrentUser.LoginName;

                                isNew = true;

                                var crep = new CompanyRepository(web);
                                _item = crep.GetCompanyById(_id);
                            }

                            Logger.LogInfo("SaveButtonClick: before asking existing item", GetType().ToString());
                            item = web.Lists["Lehed"].GetItemById(Item.Id); //web.GetListItem(web.Url + "/" + Item.Url);
                            oldName = item.Title;

                            _id = item.ID;
                            publishingPage = PublishingPage.GetPublishingPage(item);
                            pageName = publishingPage.ListItem.File.Name;

                            redir = pageName;
                            Logger.LogInfo("SaveButtonClick: before check out", GetType().ToString());

                            try
                            {
                                if (publishingPage.ListItem.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                                {
                                    publishingPage.CheckOut();
                                }
                                else if(publishingPage.ListItem.File.CheckedOutBy != null)
                                    if(publishingPage.ListItem.File.CheckedOutBy.LoginName != SPContext.Current.Web.CurrentUser.LoginName)
                                    {
                                        publishingPage.ListItem.File.UndoCheckOut();
                                        publishingPage.CheckOut();
                                    }

                            }
                            catch (Exception ex)
                            {
                                Logger.LogException(ex);
                            }

                            publishingPage.ListItem["Title"] = nameField.Text;
                            publishingPage.ListItem["ContentTypeId"] = item.Web.Site.RootWeb.ContentTypes["Firma"].Id;
                            publishingPage.ListItem[GetFieldId("Tanav")] = streetField.Text;
                            publishingPage.ListItem[GetFieldId("Postiindeks")] = zipField.Text;
                            publishingPage.ListItem[GetFieldId("WorkCity")] = cityField.Text;
                            if (!urlField.Text.StartsWith("http://") && !urlField.Text.StartsWith("https://"))
                                urlField.Text = "http://" + urlField.Text;
                            publishingPage.ListItem["WebPage"] = urlField.Text;
                            publishingPage.ListItem["Employees"] = employeesList.SelectedValue;
                            publishingPage.ListItem[GetFieldId("PartnershipLevel")] = partnershipLevel.SelectedValue;

                            int cert2;
                            int.TryParse(certifiedEmployeesField.Text, out cert2);

                            publishingPage.ListItem["CertifiedEmployees"] = cert2;
                            publishingPage.ListItem["Kontaktisik"] = contactField.Text;
                            publishingPage.ListItem["KontaktisikuEmail"] = contactEmailField.Text;
                            publishingPage.ListItem["KontaktisikuTelefon"] = contactPhoneField.Text;
                            publishingPage.ListItem["PublishingPageContent"] = descriptionField.Text;
                            if (string.IsNullOrEmpty(Request.QueryString["ID"]))
                            {
                                publishingPage.ListItem["Author"] = currentUser;
                                publishingPage.ListItem["RealAuthor"] = currentUser;
                            }
                            publishingPage.ListItem["Editor"] = web.SiteUsers[currentUser.LoginName];
                            publishingPage.ListItem["ContentType"] = "Firma";

                            var selectedOffices = new SPFieldLookupValueCollection();
                            foreach (ListItem officeItem in officesList.Items)
                                if (officeItem.Selected)
                                {
                                    var officeId = int.Parse(officeItem.Value);
                                    var officeLookup = new SPFieldLookupValue(officeId, officeItem.Text);
                                    selectedOffices.Add(officeLookup);
                                }

                            publishingPage.ListItem["Kontorid"] = selectedOffices;

                            Logger.LogInfo("SaveButtonClick: Omistatud", GetType().ToString());

                            try
                            {
                                Logger.LogInfo("SaveButtonClick: Updating file", GetType().ToString());
                                publishingPage.ListItem.File.Update();
                                Logger.LogInfo("SaveButtonClick: Updating page", GetType().ToString());
                                publishingPage.Update();
                                //publishingPage.ListItem.ParentList.Update();
                            }
                            catch (Exception ex)
                            {
                                Logger.LogException(ex);
                            }

                            try
                            {
                                Logger.LogInfo("SaveButtonClick: Checking in", GetType().ToString());
                                item.File.CheckIn(string.Empty, SPCheckinType.MajorCheckIn);
                                Logger.LogInfo("SaveButtonClick: Checkin succeeded", GetType().ToString());
                            }
                            catch (Exception ex)
                            {
                                Logger.LogException(ex);
                            }
                            if (Item != null)
                                try
                                {

                                    Logger.LogInfo("SaveButtonClick: oldname=" + oldName, GetType().ToString());
                                    Logger.LogInfo("SaveButtonClick: newname=" + nameField.Text, GetType().ToString());

                                    if (oldName == nameField.Text)
                                    {
                                        Logger.LogInfo("SaveButtonClick: Publishing existing page", GetType().ToString());
                                        if (publishingPage.ListItem.Level == SPFileLevel.Checkout)
                                            publishingPage.ListItem.File.CheckIn("");

                                            publishingPage.ListItem.File.Publish(string.Empty);
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                                        {
                                            var newUrl = "/firmad/Lehed/" + UrlHelper.GetPageFileName(nameField.Text);
                                            publishingPage.ListItem.File.MoveTo(newUrl, true);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogException(ex);
                                }

                Logger.LogInfo("SaveButtonClick: Managing images", GetType().ToString());

                if (logoUpload.HasFile)
                {
                    try
                    {
                        var img = System.Drawing.Image.FromStream(logoUpload.FileContent);
                        img.Dispose();
                    }
                    catch (Exception)
                    {
                        _errors.Add("logo",
                                    "Firma logofaili laadimine ebaõnnestus. Palun kontrolli, et logofail oleks korrektne.");
                        ApplyErrors(_errors);
                        return;
                    }

                        var sec = new SPSecurity.CodeToRunElevated(delegate
                                                                       {
                                                                           using (var rootSite = new SPSite(siteId))
                                                                           {
                                                                               using (var rootWeb = rootSite.OpenWeb())
                                                                               {
                                                                                   rootSite.AllowUnsafeUpdates = true;
                                                                                   rootWeb.AllowUnsafeUpdates = true;

                                                                                   var mem = new MemoryStream();
                                                                                   try
                                                                                   {
                                                                                       ResizeImage(200, 120,
                                                                                                   logoUpload.
                                                                                                       FileContent, mem);
                                                                                   }
                                                                                   catch
                                                                                   {
                                                                                       _errors.Add("logo",
                                                                                                   Resources.Companies.LogoLoadingFailed);
                                                                                       return;
                                                                                   }
                                                                                   var files =
                                                                                       rootWeb.GetFolder(
                                                                                           "SiteCollectionImages/firmad/")
                                                                                           .Files;
                                                                                   var spf =
                                                                                       files.Add(
                                                                                           files.Folder.Url + "/" +
                                                                                           pageName.Replace(".aspx",
                                                                                                            ".png"),
                                                                                           mem.ToArray(), true);
                                                                                   var newItem = spf.Item;
                                                                                   newItem.Update();
                                                                                   spf.Update();
                                                                                   newItem.ParentList.Update();
                                                                                   mem.Dispose();

                                                                                   Logger.LogInfo(
                                                                                       "Firmad: suur logo salvestatud",
                                                                                       GetType().ToString());

                                                                                   mem = new MemoryStream();
                                                                                   try
                                                                                   {
                                                                                       ResizeImage(100, 60,
                                                                                                   logoUpload.
                                                                                                       FileContent, mem);
                                                                                   }
                                                                                   catch
                                                                                   {
                                                                                       _errors.Add("smallLogo",
                                                                                                   Resources.Companies.SmallLogoLoadingFailed);
                                                                                       return;
                                                                                   }

                                                                                   files =
                                                                                       rootWeb.GetFolder(
                                                                                           "SiteCollectionImages/firmad/")
                                                                                           .Files;
                                                                                   spf =
                                                                                       files.Add(
                                                                                           files.Folder.Url + "/" +
                                                                                           pageName.Replace(".aspx",
                                                                                                            "_small.png"),
                                                                                           mem.ToArray(), true);
                                                                                   newItem = spf.Item;
                                                                                   newItem.Update();
                                                                                   spf.Update();
                                                                                   newItem.ParentList.Update();
                                                                                   mem.Dispose();

                                                                               }
                                                                           }
                                                                       });
                        SPSecurity.RunWithElevatedPrivileges(sec);
                }                
            }
            catch (Exception ex)
            {
                Response.Write(new Exception("CodeLoc: " + codeLoc, ex).ToString());
                Response.End();
            }

            var ioSec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.AllWebs[webId])
                    {
                        RemoveAllTopics(web);
                        foreach (var topicId in selectedTopics)
                            InsertTopic(web, topicId);
                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(ioSec);
            HttpContext.Current.Application["IoRelationsTable"] = null;

            if (string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                var userMail = currentUser.Email;
                //var body = "<html><body style=\"font-family:arial;font-size:10pt\">";
                //body += "<p>Hei " + currentUser.Name + "!</p>";
                //body += "<p>Tänud firma lisamise eest Eneta portaali. Ettevõtte profiil avaldatakse portaali külastajatele tutvumiseks peale administraatori poolset kinnitamist.</p>";
                //body += "<p>Teavitame Sind e-meili teel kui firma andmed on avaldatud.</p>";

                //body += "<p>Tervitustega,<br/>";
                //body += "Eneta tiim</p>";
                //body += "<a href=\"http://www.eneta.ee\"><img src=\"http://www.eneta.ee/SiteCollectionImages/logod/eneta_logo_250x78_sinine.png\" border=\"0\"></a>";
                //body += "</body></html>";

                //SPUtility.SendEmail(SPContext.Current.Web, false, false, userMail, nameField.Text + " firma lisati Eneta portaali", body);
                //SPUtility.SendEmail(SPContext.Current.Web, false, false, "abi@eneta.ee", nameField.Text + " firma lisati Eneta portaali", body);

                var mailer = new MailerService();
                var addresses = new[] { userMail, "abi@eneta.ee" };
                mailer.SendMailByTemplate("CompanyAdded", currentUser.Name, nameField.Text, null, addresses);
            }

            var userId2 = SPContext.Current.Web.CurrentUser.LoginName;
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (var pubsite = new SPSite(siteId))
                using (var pubweb = pubsite.OpenWeb("/firmad/"))
                {
                    pubweb.AllowUnsafeUpdates = true;
                    var pubList = pubweb.Lists["Lehed"];

                    var cuser = pubweb.SiteUsers[userId2];

                    //var ass = pubList.RoleAssignments.GetAssignmentByPrincipal(cuser);
                    pubList.RoleAssignments.Remove(cuser);
                    pubList.Update();
                    pubweb.AllowUnsafeUpdates = false;

                }
            });                                



            var profileItem = SPContext.Current.Web.CurrentUser.GetProfile();
            if(string.IsNullOrEmpty(Request.QueryString["ID"]))
                Response.Redirect("/profile.aspx?ID=" + profileItem.ID + "&msg=compadd", true);
            else
                Response.Redirect("/profile.aspx?ID=" + profileItem.ID + "&msg=compsave", true);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var currentUser = SPContext.Current.Web.CurrentUser;
            if(currentUser == null)
            {
                Response.Redirect("/");
                return;
            }

            if(Item != null)
            {
                if (string.IsNullOrEmpty(Item.AuthorUserName))
                {
                    Response.Redirect("/");
                    return;
                }

                if (Item.AuthorUserName != currentUser.LoginName)
                    if(!currentUser.IsSiteAdmin)
                    {
                        Response.Redirect("/");
                        return;
                    }
            }

            warningBox.Style["display"] = "none";

            var keys = new string[] { "name", "description", "street", "zip", "city", "offices", "url", "cert", "contact", "contactEmail", "contactName" };
            foreach (var fieldKey in keys)
            {
                var ctl = (HtmlGenericControl)this.FindControl(fieldKey + "Container", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "Container<br>");
                    continue;
                    //Response.End();
                }
                ctl.Attributes.Add("class", "info-row");
                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorMessage", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorMessage<br>");
                    //Response.End();
                }
                else
                    ctl.Style["display"] = "none";

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorLabel", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorLabel<br>");
                    //Response.End();
                }
                else
                    ctl.InnerText = string.Empty;
            }

            if (IsPostBack)
                return;

            try
            {
                if (Request.UrlReferrer != null)
                {
                    if (fromUrlField == null)
                        Logger.LogWarning("OnLoad(): Cannot find fromUrlField", GetType().ToString());
                    else
                        fromUrlField.Value = Request.UrlReferrer.ToString();

                    if (cancelLink == null)
                        Logger.LogWarning("OnLoad(): Cannot find cancelLink", GetType().ToString());
                    else 
                        cancelLink.HRef = Request.UrlReferrer.ToString();
                }
            }
            catch(Exception ex)
            {
                Logger.LogException(ex);
            }

            Bind();
        }

        private void Bind()
        {
            var where = "";
            try
            {
                var employeesField = (SPFieldChoice)SPContext.Current.Web.Lists["Lehed"].Fields[GetFieldId("Employees")];
                foreach (var choice in employeesField.Choices)
                {
                    var listItem = new ListItem(choice, choice);
                    employeesList.Items.Add(listItem);
                }

                var partnershipField = (SPFieldChoice)SPContext.Current.Web.Lists["Lehed"].Fields[GetFieldId("PartnershipLevel")];
                foreach (var level in partnershipField.Choices)
                {
                    var listItem = new ListItem(level, level);
                    partnershipLevel.Items.Add(listItem);
                }
                where = "Before counties";
                var countiesList = SPContext.Current.Site.RootWeb.Lists["Maakond"];
                var query = new SPQuery();
                query.Query = "<OrderBy><FieldRef Name='Title' Ascending='True' /></OrderBy>";
                var counties = countiesList.GetItems(query);
                officesList.DataSource = counties;
                officesList.DataBind();

                if (Item == null)
                {
                    logoExample.Visible = false;
                    logoExample.Style["display"] = "none";
                    BindIo();
                    titleLabel.Text = Resources.Companies.NewCompany;
                    certifiedEmployeesField.Text = "0";
                    return;
                }


                titleLabel.Text = Item.Title;
                nameField.Text = Item.Title;
                //fileNameLabel.Text = Item.File.Name;
                where = "before logo";
                var logoName = Item.FileName.Replace(".aspx", ".png");
                var logoUrl = "/SiteCollectionImages/firmad/" + logoName;
                var logoFile = SPContext.Current.Site.RootWeb.GetFile(logoUrl);
                if (!logoFile.Exists)
                {
                    logoExample.Visible = false;
                    logoExample.Style["display"] = "none";
                }
                else
                {
                    logoExample.Style["display"] = "";
                    logoExample.Src = logoUrl;
                    logoExample.Visible = true;
                }

                descriptionField.Text = Item.Description;
                streetField.Text = Item.Street;
                zipField.Text = Item.Zip;
                cityField.Text = Item.City;
                urlField.Text = Item.HomePage;

                if (employeesList.Items.FindByValue(Item.Employees) != null)
                    employeesList.SelectedValue = Item.Employees;

                if (!string.IsNullOrEmpty(Item.CertifiedEmployees))
                    certifiedEmployeesField.Text = Item.CertifiedEmployees;
                else
                    certifiedEmployeesField.Text = "0";

                contactField.Text = Item.ContactName;
                contactEmailField.Text = Item.ContactEmail;
                contactPhoneField.Text = Item.ContactPhone;

                if (Item.Offices != null)
                {
                    Logger.LogInfo("Bind(): Item.Offices count: " + Item.Offices.Count, GetType().ToString());
                    foreach (var office in Item.Offices)
                        foreach (ListItem officeItem in officesList.Items)
                            if (officeItem.Value == office.Id.ToString())
                                officeItem.Selected = true;
                }
                else
                {
                    Logger.LogInfo("Bind(): Item.Offices is null", GetType().ToString());
                }

                if (partnershipLevel.Items.FindByValue(Item.PartnershipLevel) != null)
                    partnershipLevel.SelectedValue = Item.PartnershipLevel;
            }
            catch (Exception ex)
            {
                Logger.LogInfo("Bind(): Exception occured", GetType().ToString());
                Logger.LogException(ex);
                Response.Write("<!-- " + where + " -->");

            }
            BindIo();
        }

        private void BindIo()
        {
            Logger.LogInfo("BindIo(): starting", GetType().ToString());
            
            var repository = new CompanyRepository(SPContext.Current.Web);

            try
            {
                var levels = repository.GetIoLevels();

                Logger.LogInfo("BindIo(): Levels found: " + levels.Count, GetType().ToString());
                if(IOLevel1Repeater == null)
                {
                    Logger.LogInfo("BindIo(): Can't find IOLevel1Repeater", GetType().ToString());
                    return;
                }
                IOLevel1Repeater.DataSource = levels;
                IOLevel1Repeater.DataBind();
            }
            catch(Exception ex)
            {
                Logger.LogWarning("BindIo(): Exception occured", GetType().ToString());
                Logger.LogException(ex);
            }
        }

        protected void IoLevel1RepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (IoLevel1)e.Item.DataItem;

            var label = (Label)e.Item.FindControl("IOLevel1Label");
            label.Text = item.Title;

            try
            {
                var repeater = (Repeater)e.Item.FindControl("IOLevel2Repeater");
                repeater.ItemDataBound += IoLevel2RepeaterItemDataBound;
                repeater.DataSource = item.Level2Items;
                repeater.DataBind();
            }
            catch (Exception ex)
            {
                Logger.LogWarning("IoLevel1RepeaterItemDataBound: Error occured", GetType().ToString());
                Logger.LogException(ex);
            }
        }

        protected void IoLevel2RepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (IoLevel2)e.Item.DataItem;

            try
            {
                var repeater = (Repeater)e.Item.FindControl("IOTopicRepeater");
                repeater.ItemDataBound += IoTopicRepeaterItemDataBound;
                repeater.DataSource = item.Level3Items;
                repeater.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
                Response.End();
            }
        }

        protected void IoTopicRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var siteId = SPContext.Current.Site.ID;
            var webId = SPContext.Current.Web.ID;

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.AllWebs[webId])
                    {
                        if (_checkedTopics == null)
                            LoadCheckedTopics(web);

                        var item = (IoLevel3)e.Item.DataItem;

                        var tooltipLink = (HtmlAnchor) e.Item.FindControl("tooltipLink");
                        tooltipLink.HRef = "/_layouts/enetahandlers/iotooltiphandler.ashx?l3=" + item.Id + "&width=216";

                        var label = (Label)e.Item.FindControl("IOTopicLabel");
                        label.Text = item.Title;

                        var check = (CheckBox)e.Item.FindControl("IOTopicCheckBox");
                        check.InputAttributes.Add("value", item.Id.ToString());
                        check.InputAttributes.Add("style", "width:20px");

                        if(_checkedTopics != null)
                            foreach (SPListItem topicItem in _checkedTopics)
                            {
                                var objectValue = topicItem["IOTopic"];
                                if (objectValue == null)
                                    continue;

                                var value = new SPFieldLookupValue(objectValue.ToString());
                                if (value.LookupId == item.Id)
                                {
                                    check.Checked = true;
                                    break;
                                }
                            }

                        var reqProductsLabel = (Label) e.Item.FindControl("RequiredProductsLabel");
                        var repeater = (Repeater) e.Item.FindControl("RequiredProductsRepeater");
                        
                        if(item.Products.Count == 0)
                            reqProductsLabel.Text = Resources.Companies.NoRequiredProducts;
                        else 
                            reqProductsLabel.Text = Resources.Companies.RequiredProductsLabel;
                        repeater.ItemDataBound += ProductsRepeaterItemDataBound;
                        repeater.DataSource = item.Products;
                        repeater.DataBind();
                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
        }

        protected void ProductsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;
            
            var product = (IoProduct) e.Item.DataItem;
            var label = (Label) e.Item.FindControl("ProductLabel");
            var link = (HtmlAnchor) e.Item.FindControl("ProductLink");

            label.Visible = false;
            link.Visible = false;

            if (!string.IsNullOrEmpty(product.Url))
            {
                link.HRef = product.Url;
                link.InnerText = product.Title;
                link.Visible = true;
            }
            else
            {
                label.Visible = true;
                label.Text = product.Title;
            }
        }

        private CompanyDto _item;

        private CompanyDto Item
        {
            get
            {
                if (_item != null)
                    return _item;

                var idString = Request.QueryString["ID"];
                if (string.IsNullOrEmpty(idString))
                    return null;

                int id;
                if (!int.TryParse(idString, out id))
                    return null;

                var rep = new CompanyRepository(SPContext.Current.Web);
                _item = rep.GetCompanyById(id);
                
                return _item;
            }
        }

        private Guid GetFieldId(string internalName)
        {
            try
            {
                return SPContext.Current.Web.Lists["Lehed"].Fields.GetFieldByInternalName(internalName).Id;
            }
            catch (Exception ex)
            {
                throw new Exception(internalName + " " + ex);
            }
        }
        
        private void ResizeImage(int width, int height, Stream fromStream, Stream toStream)
        {
            var image = System.Drawing.Image.FromStream(fromStream);
            var x1 = image.Width;
            var y1 = image.Height;
            var x2 = width;
            var y2 = height;
            int x11, y11;

            if (x1 <= y1)
            {
                x11 = y2 * x1 / y1;
                y11 = y2;
            }
            else
            {
                x11 = x2;
                y11 = x2 * y1 / x1;
            }

            var thumbnailBitmap = new Bitmap(x11, y11);

            var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
            thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var imageRectangle = new Rectangle(0, 0, x11, y11);
            thumbnailGraph.DrawImage(image, imageRectangle);

            //thumbnailBitmap.Save(toStream, image.RawFormat);
            thumbnailBitmap.Save(toStream, ImageFormat.Png);

            thumbnailGraph.Dispose();
            thumbnailBitmap.Dispose();
            image.Dispose();
        }
        
        private void ApplyErrors(Dictionary<string, string> errors)
        {
            var unboundErrors = new List<string>();

            if (errors.Count == 0)
                return;

            foreach (string fieldKey in errors.Keys)
            {
                var error = errors[fieldKey];
                var ctl = (HtmlGenericControl)this.FindControl(fieldKey + "Container", true);
                if (ctl == null)
                {
                    unboundErrors.Add(error);
                    continue;
                    //Response.End();
                }
                ctl.Attributes.Add("class", "info-row failed-info");
                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorMessage", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorMessage<br>");
                    //Response.End();
                }
                else 
                    ctl.Style["display"] = "";

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorLabel", true);
                if (ctl == null)
                {
                    //Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorLabel<br>");
                    //Response.End();
                }
                else 
                    ctl.InnerText = error;
            }
            foreach (var err in unboundErrors)
                Logger.LogInfo("ApplyErrors: Unbound error: " + err, GetType().ToString());
            errorsRepeater.DataSource = unboundErrors;
            errorsRepeater.DataBind();
            Logger.LogInfo("ApplyErrors: Display", GetType().ToString());
            Logger.LogInfo("EnableViewState: " + EnableViewState, GetType().ToString());
            warningBox.Style["display"] = "";
            ViewState["Errors"] = errors;
        }

        private SPListItemCollection _checkedTopics;

        private void LoadCheckedTopics(SPWeb web)
        {
            var list = web.Lists["IOCompany"];

            var queryString = "<Where><Eq><FieldRef Name='Company' LookupId='true' /><Value Type='Lookup'>{0}</Value></Eq></Where>";
            queryString = string.Format(queryString, Request.QueryString["ID"]);

            var query = new SPQuery();
            query.Query = queryString;

            var items = list.GetItems(query);
            _checkedTopics = items;
        }

        private void RemoveAllTopics(SPWeb web)
        {
            if (_checkedTopics == null)
                LoadCheckedTopics(web);
            if (_checkedTopics == null)
                return;

            for (var i = _checkedTopics.Count - 1; i >= 0; i--)
            {
                _checkedTopics.Delete(i);
            }
        }

        private void InsertTopic(SPWeb web, int topicId)
        {
            var list = web.Lists["IOCompany"];
            var item = list.Items.Add();
            item["Company"] = _id;
            item["IOTopic"] = topicId;
            item.Update();
            list.Update();
        }

        private int[] GetSelectedTopics()
        {
            var topics = new List<int>();
            foreach (RepeaterItem level1Item in IOLevel1Repeater.Items)
            {
                var level2Repeater = (Repeater)level1Item.FindControl("IOLevel2Repeater");
                if (level2Repeater == null)
                {
                    //Log("Cannot find level2Repeater");
                    continue;
                }
                //Log("Level2 repeater found");
                //Log("Level2 repeater items: " + level2Repeater.Items.Count);
                foreach (RepeaterItem level2Item in level2Repeater.Items)
                {
                    var topicRepeater = (Repeater)level2Item.FindControl("IOTopicRepeater");
                    if (topicRepeater == null)
                        continue;

                    foreach (RepeaterItem topicItem in topicRepeater.Items)
                    {
                        var check = (CheckBox)topicItem.FindControl("IOTopicCheckBox");
                        if (check.Checked)
                            topics.Add(int.Parse(check.InputAttributes["value"]));
                    }
                }
            }
            return topics.ToArray();
        }

        private string GetFileName()
        {
            var replacements = new Dictionary<string, string>
                                   {
                                       {"õ", "o"},
                                       {"ä", "a"},
                                       {"ö", "o"},
                                       {"ü", "u"},
                                       {"Õ", "o"},
                                       {"Ä", "a"},
                                       {"Ö", "o"},
                                       {"Ü", "u"},
                                       {" ", "-"}
                                   };

            var pageName = nameField.Text;
            foreach (var s in replacements.Keys)
                pageName = pageName.Replace(s, replacements[s]);
            pageName += ".aspx";
            return pageName;
        }
    }
}
